<template>
    <section class="carousel-wrap">
        <ul class="list" v-if="list.length > 0" :style="{top: `${-top}px`}">
            <li
                class="item"
                v-for="item in list"
                :key="item.id"
                v-text="item.text"
                :title="item.text"
                
                ref="item"
            ></li>
        </ul>
    </section>
</template>

<script>

export default {
    data () {
        return {
            list: [],
            top: 0
        };
    },

    props: {
        dataSource: {
            type: Array,
            default () {
                return [];
            }
        }
    },

    watch: {
        dataSource: {
            handler (newList, oldList) {
                this.list = JSON.parse(JSON.stringify(newList));
                clearTimeout(this.timeout);
                this.timeout = setTimeout(this._moveEvent, 1000);
            },
            deep: true
        }
    },

    created () {
        this._moveEvent();
    },

    methods: {
        _moveEvent () {
            this.$nextTick(() => {
                let aItem = this.$refs.item;
                this.top = 0;
                // 只有一条数据或者没有数据时不运动
                if (!aItem || aItem.length <= 1) {
                    return false;
                }
                // 运动高度
                let h = aItem[0].offsetHeight;
                clearInterval(this.timer);
                this.interval = setInterval(() => {
                    this.top++;
                    if (this.top >= h) {
                        this.$emit('moveOk');
                        this.top = 0;
                        clearInterval(this.interval);
                    }
                }, 27);
            });
        }
    }
}
</script>

<style lang="scss" scoped>
    .carousel-wrap {
        overflow: hidden;
        width: 500px;
        height: 30px;
        margin: 30px auto 0;
        border: 1px solid #399;
        position: relative;
        .list {
            width: 100%;
            position: absolute;
            top: 0;
            left: 0;
        }
        .list .item {
            height: 30px;
            line-height: 30px;
            text-align: center;

            white-space:nowrap; 
            text-overflow:ellipsis; 
            overflow:hidden;
        }
    }
</style>